package com.steven.im.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.squareup.picasso.Picasso;
import com.steven.putorefresh.BaseBothListener;
import com.steven.putorefresh.PullToBothLayout;
import com.steven.im.App;
import com.steven.im.R;
import com.steven.im.adapter.HomeBottomRecycleAdapter;
import com.steven.im.adapter.HomeCenterRecycleAdapter;
import com.steven.im.base.BaseFragment;
import com.steven.im.customprovider.GridItemDecoration;
import com.steven.im.entity.BaseEntity;
import com.steven.im.entity.BaseEventEntity;
import com.steven.im.entity.HomeCategoryEntity;
import com.steven.im.imageLoader.GlideImageLoader;
import com.steven.im.net.MyCallback;
import com.steven.im.net.Task;
import com.steven.im.ui.activity.GoodsDetailActivity;
import com.steven.im.ui.activity.WebActivity;
import com.steven.im.utils.ChangeTvColorUtils;
import com.steven.im.utils.GlobalActionUtils;
import com.steven.im.utils.SPUtils;
import com.steven.im.utils.ScreenUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;

import static android.os.Build.VERSION_CODES.KITKAT;

/**
 * Created by Steven on 2019/3/1.
 */
public class HomeFragment extends BaseFragment {

    private boolean isFirst = true;//默认第一次加载
    private JSONArray bannerList = new JSONArray();//banner
    private JSONArray categoryList = new JSONArray();//中间图标
    private JSONArray goodsList = new JSONArray();//商品列表
    private JSONArray newsList = new JSONArray();//商品列表
    private JSONArray newsGoodsList = new JSONArray();//推荐模块
    private List<HomeCategoryEntity> categoryEntityList = new ArrayList<>();
    private HomeBottomRecycleAdapter myAdapter;
    private HomeCenterRecycleAdapter myCenterAdapter;
    @BindView(R.id.view_status_bar_place)
    View statusBarPlace;
    @BindView(R.id.mBanner)
    Banner mBanner;

    @BindView(R.id.mRecycleView)
    RecyclerView recyclerView;

    @BindView(R.id.mRecycleView_goods)
    RecyclerView mRecycleView_goods;
    @BindView(R.id.pullRefreshBoth)
    PullToBothLayout pullRefreshBoth;
    @BindView(R.id.tv_news)
    TextView tv_news;
    @BindView(R.id.vf_notice_scroll)
    ViewFlipper noticeScroll;


    @BindView(R.id.ll_recommended)
    LinearLayout ll_recommended;
    @BindView(R.id.iv_leftGood)
    ImageView iv_leftGood;
    @BindView(R.id.tv_left_name)
    TextView tv_left_name;
    @BindView(R.id.tv_left_detail)
    TextView tv_left_detail;
    @BindView(R.id.tv_right_top_name)
    TextView tv_right_top_name;
    @BindView(R.id.tv_right_top_detail)
    TextView tv_right_top_detail;
    @BindView(R.id.iv_right_top_good)
    ImageView iv_right_top_good;
    @BindView(R.id.tv_right_bottom_name)
    TextView tv_right_bottom_name;
    @BindView(R.id.tv_right_bottom_detail)
    TextView tv_right_bottom_detail;
    @BindView(R.id.iv_right_bottom_good)
    ImageView iv_right_bottom_good;

    private boolean isRefreshNow = true;//默认上去得开启刷新
    private boolean isHide = false;//默认该页面是没有隐藏的
    private boolean isRefreshIng = false;//判断是不是正在刷新
    private long refreshTime;
    public static boolean isLoadData = false;//判断是不是加载数据

    private void toGoodsDetail(int i) {
        if (newsGoodsList != null && newsGoodsList.size() >= (i + 1)) {
            startActivity(new Intent(getActivity(), GoodsDetailActivity.class)
                    .putExtra("issuedNo", JSON.parseObject(newsGoodsList.getString(i)).getString("issuedNo")));
        }
    }

    @OnClick({R.id.ll_left, R.id.ll_right_top, R.id.ll_right_bottom, R.id.tv_news})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.ll_left:
                toGoodsDetail(0);
                break;
            case R.id.ll_right_top:
                toGoodsDetail(1);
                break;
            case R.id.ll_right_bottom:
                toGoodsDetail(2);
                break;
            case R.id.tv_news:
                String linkUrl;
                if (newsList != null && newsList.size() >= 1)
                    if (JSON.parseObject(newsList.getString(0)).containsKey("linkUrl")) {
                        linkUrl = JSON.parseObject(newsList.getString(0)).getString("linkUrl");
                        if (!linkUrl.equals("#")) {
                            startActivity(new Intent(getActivity(), WebActivity.class).putExtra("url", linkUrl));
                        }
                    }
                break;
        }
    }

    //更新 推荐商品列表
    private void setRecommendedGoods() {
        if (newsGoodsList.size() >= 3) {
            ll_recommended.setVisibility(View.VISIBLE);
            JSONObject jsonObject_1 = JSON.parseObject(newsGoodsList.getString(0));
            tv_left_name.setText(jsonObject_1.getString("goodsTitle"));
            tv_left_detail.setText(jsonObject_1.getString("description"));
            Picasso.with(App.getContext()).load(jsonObject_1.getString("previewImage")).placeholder(R.drawable.home_product).error(R.drawable.home_product).into(iv_leftGood);

            JSONObject jsonObject_2 = JSON.parseObject(newsGoodsList.getString(1));
            tv_right_top_name.setText(jsonObject_2.getString("goodsTitle"));
            tv_right_top_detail.setText(jsonObject_2.getString("description"));
            Picasso.with(App.getContext()).load(jsonObject_2.getString("previewImage")).placeholder(R.drawable.home_product).error(R.drawable.home_product).into(iv_right_top_good);

            JSONObject jsonObject_3 = JSON.parseObject(newsGoodsList.getString(2));
            tv_right_bottom_name.setText(jsonObject_3.getString("goodsTitle"));
            tv_right_bottom_detail.setText(jsonObject_3.getString("description"));
            Picasso.with(App.getContext()).load(jsonObject_3.getString("previewImage")).placeholder(R.drawable.home_product).error(R.drawable.home_product).into(iv_right_bottom_good);
        }
    }

    @SuppressLint("InflateParams")
    @Override
    public View setContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_home, null);
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
        refreshTime = Long.parseLong(SPUtils.get(App.getContext(), "refreshDelayTime", "3000").toString());
        //初始化组件
        if (Build.VERSION.SDK_INT <= KITKAT) {
            statusBarPlace.setVisibility(View.VISIBLE);
            int height = ScreenUtil.getStatusBarHeight(getContext());
            ViewGroup.LayoutParams params;
            params = statusBarPlace.getLayoutParams();
            params.height = height;
            statusBarPlace.setLayoutParams(params);
            params = mBanner.getLayoutParams();
            params.height = 200 - height;
            mBanner.setLayoutParams(params);
        }
        setListener();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        isHide = hidden;
        if (!hidden) {
            isRefreshNow = true;//开启即可刷新
            loadData();
        } else {
            isRefreshNow = false;
            isRefreshIng = false;
            mHandler.removeMessages(-1);
        }
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(BaseEventEntity baseEventEntity) {
        //获取出价记录  然后进行设置
        try {
            String title = baseEventEntity.getTitle();
            switch (title) {
                case "home": //首页刷新机制控制
                    if (!baseEventEntity.getResult().getBoolean("isStop") && !isHide) {
                        isRefreshNow = true;
                        if (!isRefreshIng) {
                            isRefreshIng = true;
                            mHandler.removeMessages(-1);
                            mHandler.sendEmptyMessageDelayed(-1, refreshTime);
                            loadData();
                        }
                    } else {
                        isRefreshIng = false;
                        isRefreshNow = false;
                    }
                    break;
                case "timeEnd"://预售商品倒计时结束 进行处理
                    setTimeEnd(Integer.parseInt(baseEventEntity.getResult().getString("position")));
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //处理预售状态下  倒计时 结束
    private void setTimeEnd(int position) {
        goodsList.getJSONObject(position).put("goodsStatus", "20");
    }

    //处理刷新任务
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case -1:
                    //处理刷新
                    if (isRefreshNow && !isFirst) {  //只有竞拍商品才能刷新
                        isRefreshIng = true;
                        refresh();
                    }
                    break;
            }
        }
    };

    //实时刷新
    private void refresh() {
        StringBuilder buf = new StringBuilder();
        for (int i = 0; i < goodsList.size(); i++) {
            JSONObject jsonObject = JSON.parseObject(goodsList.getString(i));
            if ("1".equals(jsonObject.getString("salesType"))) {//表示是竞拍商品 并且还是竞拍状态
                buf.append(JSON.parseObject(goodsList.getString(i)).getString("goodsId")).append(",");
            }
        }
        if (!buf.toString().equals("")) {
            String[] list = buf.toString().trim().split(",");
            Task.getApiService().refreshHome(list).enqueue(new MyCallback<BaseEntity>(getActivity()) {
                @Override
                protected void onSuccess(Response<BaseEntity> response) {
                    if ("0".equals(response.body().getCode())) {
                        if (response.body().getResult().getJSONArray("goodsList").size() > 0) {
                            //设置界面信息
                            JSONArray bid_goodsList = response.body().getResult().getJSONArray("goodsList");
                            for (int i = 0; i < bid_goodsList.size(); i++) {
                                for (int k = 0; k < goodsList.size(); k++) {
                                    if ((JSON.parseObject(bid_goodsList.getString(i)).getString("goodsId")).equals((JSON.parseObject(goodsList.getString(k)).getString("goodsId")))) {
                                        //表示goodId一样的直接进行设置
                                        String status = JSON.parseObject(bid_goodsList.getString(i)).getString("biddingStatus");
                                        switch (status) {
                                            case "10"://预售
                                                goodsList.getJSONObject(k).put("publishCountdown", JSON.parseObject(bid_goodsList.getString(i)).getString("biddingCountdown"));//设置成功
                                                break;
                                            case "20"://竞拍
                                                goodsList.getJSONObject(k).put("biddingCountdown", JSON.parseObject(bid_goodsList.getString(i)).getString("biddingCountdown"));//设置成功
                                                break;
                                        }
//                                        goodsList.getJSONObject(k).put("biddingCountdown", JSON.parseObject(bid_goodsList.getString(i)).getString("biddingCountdown"));//设置成功
                                        goodsList.getJSONObject(k).put("goodsStatus", JSON.parseObject(bid_goodsList.getString(i)).getString("biddingStatus"));
                                        goodsList.getJSONObject(k).put("biddingPrice", JSON.parseObject(bid_goodsList.getString(i)).getString("biddingPrice"));
                                        goodsList.getJSONObject(k).put("issuedNo", JSON.parseObject(bid_goodsList.getString(i)).getString("issuedNo"));
                                        myAdapter.cancelOneTimes(JSON.parseObject(bid_goodsList.getString(i)).getString("goodsId"));
                                        myAdapter.notifyItemChanged(k);
                                    }
                                }
                            }
                        }
                        if (response.body().getResult().getJSONArray("newsList").size() > 0) {
                            newsList.clear();
                            newsList.addAll(response.body().getResult().getJSONArray("newsList"));
                            startFlipping();
                        }
                        mHandler.removeMessages(-1);
                        mHandler.sendEmptyMessageDelayed(-1, refreshTime);
                    }
                }

                @Override
                protected void onFailure(Throwable t) {

                }
            });
        } else {
            //表示不进行刷新 但不停止查询
            mHandler.removeMessages(-1);
            mHandler.sendEmptyMessageDelayed(-1, refreshTime);
        }
    }

    //初始化banner轮播
    private void setBanner() {
        List<String> url = new ArrayList<>();//图片url
        final List<String> title = new ArrayList<>();//图片标题
        final List<String> linkUrl = new ArrayList<>();//图片linkUrl
        for (int i = 0; i < bannerList.size(); i++) {
            url.add(JSON.parseObject(bannerList.getString(i)).getString("url"));
            title.add(JSON.parseObject(bannerList.getString(i)).getString("title"));
            linkUrl.add(JSON.parseObject(bannerList.getString(i)).getString("linkUrl"));
        }
        //        //设置banner样式
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        mBanner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        mBanner.setImages(url);
        //设置banner动画效果
        mBanner.setBannerAnimation(Transformer.DepthPage);
        //设置自动轮播，默认为true
        mBanner.isAutoPlay(true);
        //设置轮播时间
        mBanner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        mBanner.setIndicatorGravity(BannerConfig.CENTER);
        mBanner.start();
        mBanner.startAutoPlay();
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                startActivity(new Intent(getActivity(), WebActivity.class).putExtra("title", title.get(position)).putExtra("url", linkUrl.get(position)));
            }
        });
    }

    //初始化中间导航九宫格
    private void setCenterGridView() {
        categoryEntityList.clear();
        //纵向线性布局
        for (int i = 0; i < categoryList.size(); i++) {
            HomeCategoryEntity homeCategoryEntity = new HomeCategoryEntity();
            homeCategoryEntity.setTitle(JSON.parseObject(categoryList.getString(i)).getString("title"));
            homeCategoryEntity.setIconUrl(JSON.parseObject(categoryList.getString(i)).getString("iconUrl"));
            homeCategoryEntity.setActionType(JSON.parseObject(categoryList.getString(i)).getString("actionType"));
            homeCategoryEntity.setActionUrl(JSON.parseObject(categoryList.getString(i)).getString("actionUrl"));
            categoryEntityList.add(homeCategoryEntity);
        }
        if (isFirst) {
            myCenterAdapter = new HomeCenterRecycleAdapter(categoryEntityList);
            GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 4);
            recyclerView.setHasFixedSize(true);
            recyclerView.setLayoutManager(layoutManager);
            GridItemDecoration divider = new GridItemDecoration.Builder(Objects.requireNonNull(getActivity()))
                    .setHorizontalSpan(R.dimen.common_vew_column_padding)
                    .setVerticalSpan(R.dimen.common_vew_raw_padding)
                    .setColorResource(R.color.bg_gray)
                    .setShowLastLine(false)
                    .build();
            recyclerView.addItemDecoration(divider);
            recyclerView.setAdapter(myCenterAdapter);
        } else {
            myCenterAdapter.notifyDataSetChanged();
        }

        myCenterAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                GlobalActionUtils.toPage(categoryEntityList.get(position).getActionType(),
                        (Object) categoryEntityList.get(position).getActionUrl(), getActivity());
            }
        });
    }

    //初始化商品列表
    private void setGoodsList() {
        //纵向线性布局
        myAdapter = new HomeBottomRecycleAdapter(goodsList);
        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 2);
        mRecycleView_goods.setHasFixedSize(true);
        mRecycleView_goods.setLayoutManager(layoutManager);
        mRecycleView_goods.setNestedScrollingEnabled(false);
        GridItemDecoration divider = new GridItemDecoration.Builder(Objects.requireNonNull(getActivity()))
                .setHorizontalSpan(R.dimen.common_vew_column_padding)
                .setVerticalSpan(R.dimen.common_vew_raw_padding)
                .setColorResource(R.color.bg_gray)
                .setShowLastLine(false)
                .build();
        mRecycleView_goods.addItemDecoration(divider);
        myAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                JSONObject jsonObject = JSON.parseObject(goodsList.getString(position));
                startActivity(new Intent(getActivity(), GoodsDetailActivity.class)
                        .putExtra("goodId", jsonObject.getString("goodsId")).putExtra("issuedNo", jsonObject.getString("issuedNo"))
                );
            }
        });
        ((SimpleItemAnimator) mRecycleView_goods.getItemAnimator()).setSupportsChangeAnimations(false);
        mRecycleView_goods.setAdapter(myAdapter);
    }

    //设置监听
    private void setListener() {
        pullRefreshBoth.setCanLoadMore(false);
        pullRefreshBoth.setRefreshListener(new BaseBothListener() {
            @Override
            public void refresh() {
                loadData();
            }

            @Override
            public void loadMore() {

            }
        });

    }

    //设置上下滚动
    private void startFlipping() {
        if (newsList != null && !newsList.isEmpty())
            tv_news.setText(ChangeTvColorUtils.textColor(JSON.parseObject(newsList.getString(0)).getString("title"), "「", "」", R.color.mainBg));
    }

    //获取数据
    private void loadData() {
        isLoadData = true;
        Task.getApiService().getHomeDetails().enqueue(new MyCallback<BaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                try {
                    if ("0".equals(response.body().getCode())) {
                        goodsList.clear();
                        goodsList.addAll(response.body().getResult().getJSONArray("goodsList"));
                        bannerList.clear();
                        bannerList.addAll(response.body().getResult().getJSONArray("bannerList"));
                        newsList.clear();
                        newsList.addAll(response.body().getResult().getJSONArray("newsList"));
                        if (response.body().getResult().containsKey("newGoodsList")) {
                            newsGoodsList.clear();
                            newsGoodsList.addAll(response.body().getResult().getJSONArray("newGoodsList"));
                        }
                        categoryList.clear();
                        categoryList.addAll(response.body().getResult().getJSONArray("categoryList"));
                        setBanner();
                        setCenterGridView();
                        setRecommendedGoods();
                        startFlipping();
                        if (isFirst) {
                            setGoodsList();
                            isFirst = false;
                        } else {
                            myAdapter.cancelAllTimers();
                            myAdapter.notifyDataSetChanged();
                        }
                        if (!isRefreshIng) {
                            isRefreshIng = true;
                            mHandler.sendEmptyMessageDelayed(-1, refreshTime);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (pullRefreshBoth != null)
                    pullRefreshBoth.finishRefresh();
            }

            @Override
            protected void onFailure(Throwable t) {
                if (pullRefreshBoth != null)
                    pullRefreshBoth.finishRefresh();
                t.printStackTrace();
            }
        });
        isLoadData = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (myAdapter != null) {
            myAdapter.cancelAllTimers();
        }
        EventBus.getDefault().unregister(this);
    }
}
